<template>
  <div>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="borrowRecordId" label="借阅ID" width="100" align="center"></el-table-column>
      <el-table-column prop="user.username" label="借阅人" width="180"></el-table-column>
      <el-table-column prop="book.name" label="图书名称"></el-table-column>
      <el-table-column prop="borrowTime" label="借阅时间" width="180">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.borrowTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="returnTime" label="归还时间" width="180">
        <template slot-scope="scope">
          {{ scope.row.returnTime ? formatDateTime(scope.row.returnTime) : '-' }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="120" align="center">
        <template slot-scope="scope">
          <el-button 
            @click="handleApprove(scope.row)" 
            type="text" 
            size="small"
            v-if="!scope.row.approved">
            批准
          </el-button>
          <el-button 
            @click="handleReturn(scope.row)" 
            type="text" 
            size="small"
            v-if="scope.row.approved && !scope.row.returnTime">
            归还
          </el-button>
          <el-button
            @click="handleDelete(scope.row)"
            type="text"
            size="small"
            style="color: #F56C6C">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination 
      background 
      layout="prev, pager, next, jumper, ->, total"
      :page-size="pageSize" 
      :total="total" 
      :current-page="currentPage"
      @current-change="page"
      style="margin-top: 20px;">
    </el-pagination>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 5,
      total: 0,
      tableData: []
    }
  },
  methods: {
    formatDateTime(isoString) {
      if (!isoString) return '-';
      const date = new Date(isoString);
      return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
    },
    page(currentPage) {
      this.currentPage = currentPage
      this.fetchData()
    },
    fetchData() {
      const _this = this;
      axios.get(`http://localhost:8181/borrow/findAll/${this.currentPage-1}/${this.pageSize}`)
        .then(function(resp) {
          console.log('API响应数据:', resp.data);
          if(resp.data && resp.data.data) {
            _this.tableData = resp.data.data;
            _this.total = resp.data.total;
          } else {
            console.warn('API返回数据格式不正确:', resp.data);
            _this.$message.warning('数据格式异常');
          }
        })
        .catch(error => {
          console.error('获取借阅记录失败:', error);
          _this.$message.error('加载借阅记录失败');
        });
    },
    handleApprove(record) {
      const _this = this;
      if (!record || !record.borrowRecordId || isNaN(record.borrowRecordId)) {
        this.$message.error('无效的借阅记录ID');
        return;
      }
      this.$confirm('确认批准该借阅请求吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const borrowId = parseInt(record.borrowRecordId);
        axios.put(`http://localhost:8181/borrow/approve/${borrowId}`)
          .then(function(resp) {
            if(resp.data === 'success') {
              _this.$message.success('批准成功');
              _this.fetchData();
            }
          })
          .catch(error => {
            console.error('批准失败:', error);
            _this.$message.error('批准失败');
          });
      }).catch(() => {
        this.$message.info('已取消批准');
      });
    },
    handleDelete(record) {
      const _this = this
      this.$confirm('确认删除该借阅记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (!record || !record.borrowRecordId || isNaN(record.borrowRecordId)) {
          this.$message.error('无效的借阅记录ID')
          return
        }
        const borrowId = parseInt(record.borrowRecordId)
        axios.delete(`http://localhost:8181/borrow/delete/${borrowId}`)
          .then(function(resp) {
            if(resp.data === 'success') {
              _this.$message.success('删除成功')
              _this.fetchData()
            }
          })
          .catch(error => {
            console.error('删除失败:', error)
            _this.$message.error('删除失败')
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    handleReturn(record) {
      const _this = this;
      if (!record || !record.borrowRecordId || isNaN(record.borrowRecordId)) {
        this.$message.error('无效的借阅记录ID');
        return;
      }
      this.$confirm('确认归还该图书吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const borrowId = parseInt(record.borrowRecordId);
        axios.put(`http://localhost:8181/borrow/return/${borrowId}`)
          .then(function(resp) {
            if(resp.data === 'success') {
              _this.$message.success('归还成功');
              _this.fetchData();
            }
          })
          .catch(error => {
            console.error('归还失败:', error);
            _this.$message.error('归还失败');
          });
      }).catch(() => {
        this.$message.info('已取消归还');
      });
    }
  },
  created() {
    this.fetchData()
  }
}
</script>
